<template>

  <el-drawer size="90%" title="修改商品属性"
             v-model="editProp">
    <el-button plain type="primary" @click="saveDraft">提交修改</el-button>
    <traffic-description  :origin="traffic" :edit="trafficDraft"></traffic-description>
  </el-drawer>

  <el-collapse v-model="activeNames">
    <el-collapse-item v-loading="trafficLoading" title="资源详情" name="1">
      <el-descriptions border :column="4">
        <el-descriptions-item label="资源编号">{{ traffic.trafficNo }}</el-descriptions-item>
        <el-descriptions-item label="资源名称">{{ traffic.trafficName }}</el-descriptions-item>
        <el-descriptions-item label="出发时间">{{ traffic.startTime }}</el-descriptions-item>
        <el-descriptions-item label="到达时间">{{ traffic.reachTime }}</el-descriptions-item>
        <el-descriptions-item label="出发城市">{{ cityToStr(traffic.startCity) }}</el-descriptions-item>
        <el-descriptions-item label="到达城市">{{ cityToStr(traffic.destCity) }}</el-descriptions-item>
        <el-descriptions-item label="出发地址">{{ traffic.startAddress }}</el-descriptions-item>
        <el-descriptions-item label="到达地址">{{ traffic.destAddress }}</el-descriptions-item>
        <el-descriptions-item label="负责人电话">{{ traffic.phone }}</el-descriptions-item>
        <el-descriptions-item label="预设库存">{{ traffic.defaultStore }}</el-descriptions-item>
        <el-descriptions-item label="预设价格">{{ traffic.defaultPrice }}</el-descriptions-item>
        <el-descriptions-item label="开放天数">{{ traffic.openDay }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ traffic.updateTime }}</el-descriptions-item>
        <el-descriptions-item label="上下架状态" :declare-var="hereSellState=sellState[traffic.sellState]">
          <el-tag :type="hereSellState?.tagType">{{ hereSellState?.str }}</el-tag>
          <el-button type="warning" size="small"
                     v-if="traffic.sellState===1"
                     @click="updateSellState(trafficId,0)">下架产品
          </el-button>
          <el-button type="primary" size="small"
                     v-else
                     @click="updateSellState(trafficId,1)">上架产品
          </el-button>
        </el-descriptions-item>
        <el-descriptions-item label="管理状态" :declare-var="hereAdminState=adminState[traffic.adminState]">
          <el-tag :type="hereAdminState?.tagType">{{ hereAdminState?.str }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="编辑状态" :declare-var="hereEditState=editState[traffic.editState]">
          <el-tag :type="hereEditState?.tagType">{{ hereEditState?.str }}</el-tag>
          <el-button type="warning" size="small"
                     v-if="traffic.editState===1"
                     @click="updateEditState(0)">删除修改
          </el-button>
        </el-descriptions-item>
      </el-descriptions>
      <el-button @click="editProp=true" plain type="primary">编辑</el-button>
    </el-collapse-item>
    <el-collapse-item v-loading="storeLoading" title="库存详情" name="2">
      <div>
        <el-button @click="editingStore=!editingStore" v-if="!editingStore" plain type="primary">编辑</el-button>
        <el-button @click="cancelEditingStore" v-if="editingStore" plain type="primary">取消编辑</el-button>
        <el-button type="primary" v-if="editingStore" @click="insertStore">新增一天</el-button>
        <el-button type="primary" v-if="editingStore" @click="submitStore">提交修改</el-button>
      </div>

      <el-descriptions border :column="2">
        <el-descriptions-item align="center"
                              width="10px"
                              v-for="item in storeListDraft"
                              :key="item.date"
                              :label="item.date">
          <div>
            库存:{{ item.store }}
            <el-input-number :disabled="!editingStore" v-model="item.editStore"/>
          </div>
          <div>
            价格:{{ item.price }}
            <el-input-number :disabled="!editingStore" v-model="item.editPrice"/>
          </div>
          <el-tag v-if="item.isNew" style="margin: 4px">新增项，提交后生效</el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-collapse-item>
    <el-collapse-item v-loading="contentLoading" title="详情页" name="3">
      <el-button @click="editContent=true" plain type="primary">编辑</el-button>
      <div v-html="content"></div>
    </el-collapse-item>
  </el-collapse>

  <el-drawer size="90%" title="编辑产品详情" v-model="editContent">
    <el-button type="primary" @click="submitContentEdit">提交修改</el-button>
    <Toolbar
        :editor="editorRef"
        mode="default"
        style="border-bottom: 1px solid #ccc"
    />
    <Editor
        :defaultConfig="editorConfig"
        style="height: 400px; overflow-y: hidden;"
        v-model="contentDraft"
        @onCreated="editorRef=$event"
    />
  </el-drawer>

</template>
<script>
export default {name: "SupplierDetail"}
</script>
<script setup>
import {nextTick, onBeforeMount, onBeforeUnmount, provide, ref, shallowRef, watch,} from "vue";
import axios from "~/config/axios.js";
import {useRoute} from "vue-router";
import {cityToStr, dateStrToDate, showSuccessAndReload} from "~/config/utils.js";
import '@wangeditor/editor/dist/css/style.css'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import {editState, adminState, sellState, initObj} from "~/config/const.js";
import MyDescription from "~/components/TrafficDescription.vue";
import TrafficDescription from "~/components/TrafficDescription.vue";

const activeNames = ['1', '2', '3']

const trafficId = useRoute().params.id;
const traffic = ref({})
const trafficDraft = ref({})
const draftObj = ref(initObj)
const trafficLoading = ref(true)
const editProp = ref(false)
onBeforeMount(async () => {
  traffic.value = await axios.get(`/traffic/${trafficId}`);
  if (traffic.value.editState === 1 || ![0, 1].includes(traffic.value.adminState)) {
    draftObj.value = await axios.get(`/traffic/${trafficId}/draft`);
    trafficDraft.value = draftObj.value.json
  }
  if (traffic.value.editState === 0) {
    trafficDraft.value = JSON.parse(JSON.stringify(traffic.value))
  }
  trafficLoading.value = false
});
const updateSellState = (trafficId, newState) => {
  axios.post(`/traffic/${trafficId}/supplierEditSellState`, {
    afterState: newState
  }).then((res) => {
    showSuccessAndReload()
  })
}
const updateEditState = (newState) => {
  axios.delete(`/traffic/${traffic.value.trafficId}/draft`)
      .then(res => {
        showSuccessAndReload()
      })
}
const saveDraft = async () => {
  trafficDraft.value.startCityId = trafficDraft.value.startCity.cityId
  trafficDraft.value.destCityId = trafficDraft.value.destCity.cityId
  if (draftObj.value.draftId !== undefined) {
    const result = await axios.post(`/traffic/${trafficId}/supplierDraft/${draftObj.value.draftId}/${draftObj.value.updateTime}`
        , trafficDraft.value)
  } else {
    const result = await axios.post(`/traffic/${trafficId}/supplierDraft`, trafficDraft.value)
  }
  showSuccessAndReload()
}
// -------------------------------------------------------------
const storeList = ref([])
const storeListDraft = ref([])
const storeLoading = ref(true)
watch(trafficDraft, async () => {
  storeList.value = await axios.get(`/store/${trafficDraft.value.productType}/${trafficDraft.value.trafficId}`);
  storeListDraft.value = JSON.parse(JSON.stringify(storeList.value));
  storeLoading.value = false
})
const insertStore = () => {
  let lastDate = new Date();
  if (storeListDraft.value.length !== 0) {
    const lastStore = storeListDraft.value[storeListDraft.value.length - 1];
    lastDate = dateStrToDate(lastStore.date)
    lastDate.setDate(lastDate.getDate() + 1) //JavaScript will automatically update the month and year for you.
  }
  const item = {}
  item.date = lastDate.format("yyyy-MM-dd")
  item.store = trafficDraft.value.defaultStore
  item.price = trafficDraft.value.defaultPrice;
  item.isNew = true
  storeListDraft.value.push(item)
}
const submitStore = async () => {
  const submitStoreDate = []
  storeListDraft.value.forEach(item => {
    if (item.isNew || !Number.isNaN(item.editStore) || !Number.isNaN(item.editPrice)) {
      submitStoreDate.push(item)
    }
  })
  const result = await axios.patch(`/store/${trafficDraft.value.productType}/${trafficId}`, submitStoreDate)
  showSuccessAndReload()
}
const editingStore = ref(false)
const cancelEditingStore = () => {
  editingStore.value = !editingStore.value;
  storeListDraft.value = JSON.parse(JSON.stringify(storeList.value))
}

// --------------------------------------------------------------
const content = ref()
const contentDraft = ref()
const contentLoading = ref(true)
const editContent = ref(false)
const editorConfig = {placeholder: '请输入内容...', MENU_CONF: {uploadImage: {base64LimitSize: 1000 * 1024}}}

watch(traffic, async () => {
  content.value = await axios.get(`/introduce/${traffic.value.introduceId}`);
  contentLoading.value = false
})
watch(trafficDraft, async () => {
  contentDraft.value = await axios.get(`/introduce/${trafficDraft.value.introduceId}`);
})
const editorRef = shallowRef();
onBeforeUnmount(() => {
  if (editorRef.value !== undefined) {
    editorRef.value.destroy()
  }
})
const submitContentEdit = async () => {
  const submit = {
    content: contentDraft.value
  }
  if (draftObj.value.draftId !== undefined) {
    const result = await axios.post(`/traffic/${trafficId}/supplierDraftIntroduce/${draftObj.value.draftId}/${draftObj.value.updateTime}`
        , submit)
  } else {
    const result = await axios.post(`/traffic/${trafficId}/supplierDraftIntroduce`, submit)
  }
  showSuccessAndReload()

}


</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
